package com.baixun.gassystem.service.impl;


import com.baixun.gascommon.utils.R;
import com.baixun.gasentity.dto.UserOrderDto;
import com.baixun.gasentity.entity.SysDepartmentUserRoles;
import com.baixun.gassystem.mapper.SysDepartmentUserRolesMapper;
import com.baixun.gassystem.service.SysDepartmentUserRolesService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

/**
 * @program: 上海燃气驾驶舱
 * @description: sysDepartmentUserRoles实现类
 * @author: yesong
 **/
@Service
public class SysDepartmentUserRolesServiceImpl extends ServiceImpl<SysDepartmentUserRolesMapper, SysDepartmentUserRoles> implements SysDepartmentUserRolesService {

    @Autowired
    private SysDepartmentUserRolesMapper mapper;

    /**
     * 分配角色
     * @param departmentUserRoles
     * @return
     */

    @Override
    public R assignRole(SysDepartmentUserRoles departmentUserRoles) {
        Long userId = departmentUserRoles.getUserId();
        Long roleId = departmentUserRoles.getRoleId();

            SysDepartmentUserRoles userRole = new SysDepartmentUserRoles();
            userRole.setUserId(userId);
            userRole.setRoleId( roleId );  // 注意这里需要单独设置一个 roleId
            mapper.insert(userRole);  // 插入每个 userId 和 roleId 的组合
        return R.success("分配成功");
    }


    /**
     * 新增数据权限
     */
    @Override
    public List AddRoleOrder(SysDepartmentUserRoles departmentUserRoles) {
        // 查询数据库是否已存在相同的 userid
        SysDepartmentUserRoles existingRole = mapper.selectOne(new QueryWrapper<SysDepartmentUserRoles>()
                .eq("userid", departmentUserRoles.getUserId()));

        if (existingRole == null) {
            // 如果不存在相同的 userid，直接插入新的数据
            mapper.insert(departmentUserRoles);
        } else {
            existingRole.setDeptId(departmentUserRoles.getDeptId()); // 更新其他字段
            mapper.updateById(existingRole);
        }

        return Collections.singletonList(departmentUserRoles);
    }

    /**
     * 修改数据权限
     */
    @Override
    public int UpdateRoleOrder(SysDepartmentUserRoles departmentUserRoles) {
        mapper.deleteById(departmentUserRoles.getUserId());
        QueryWrapper<SysDepartmentUserRoles> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",departmentUserRoles.getUserId());

        return mapper.update(departmentUserRoles,queryWrapper);
    }


    /**
     * 查询数据权限
     */
    @Override
    public List<UserOrderDto> selectDepartmentAll(Long userId) {
        return mapper.selectDepartmentAll(userId);
    }


    /**
     * 通过用户id查询绑定的部门id
     * @param userId
     * @return 部门id集合
     */
    @Override
    public List<Long> selectDeptIdsByUserId(Long userId) {
        return mapper.selectDeptIdsByUserId(userId);
    }
}
